from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate, update_session_auth_hash
from django.contrib.auth.forms import AuthenticationForm,PasswordChangeForm,UserCreationForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import RegisterForm, LoginForm
from .models import User

# 注册
def register_view(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('index')
    else:
        form = RegisterForm()
    return render(request, 'users/register.html', {'form': form})

# 登录
def login_view(request):
    if request.method == 'POST':
        form = LoginForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            if not form.cleaned_data['remember_me']:
                request.session.set_expiry(0)
            return redirect('index')
    else:
        form = LoginForm()
    return render(request, 'users/login.html', {'form': form})

# 登出
def logout_view(request):
    logout(request)
    return redirect('index')

# 跳转 个人信息
@login_required
def profile_view(request):
    return render(request, 'users/profile.html')

# 修改密码
@login_required
def password_change_view(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, '密码修改成功！')
            return redirect('users:profile')
        else:
            for field, errors in form.errors.items():
                messages.error(request, f"{field}: {' '.join(errors)}")
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'users/password_change.html', {'form': form})

# 修改个人信息
@login_required
def profile_update_view(request):
    user = request.user

    if request.method == 'POST':
        user.nickname = request.POST.get('nickname', user.nickname)
        user.bio = request.POST.get('bio', user.bio)

        # 处理头像上传
        if 'avatar' in request.FILES:
            try:
                # 删除旧头像文件（但不会删除数据库记录）
                if user.avatar:
                    user.avatar.delete(save=False)

                # 更新头像字段
                user.avatar = request.FILES['avatar']
                user.save()

                messages.success(request, "头像更新成功！")
            except Exception as e:
                messages.error(request, f"头像上传失败: {e}")
                return redirect('users:profile_update')

        try:
            user.save()
            messages.success(request, '个人资料更新成功！')
        except Exception as e:
            messages.error(request, f'更新失败: {e}')

        return redirect('users:profile')

    return render(request, 'users/profile_update.html', {'user': user})
